<template>
  <!-- 遮罩层 -->
  <view v-if="show" class="modal-mask" @tap="handleMaskClick">
    <!-- 弹出框主体 -->
    <view class="modal-container" @tap.stop>
      <!-- 标题栏 -->
      <view class="modal-header">
        <view class="modal-title">核销完成</view>
        <view class="modal-close" @tap="handleCancel">×</view>
      </view>

      <!-- 内容区域 -->
      <view class="modal-content">
        <!-- 备注输入 -->
        <view class="form-item">
          <view class="label">备注</view>
          <textarea
            v-model="formData.remarks"
            placeholder="请输入备注信息"
            class="textarea"
            maxlength="200"
            show-confirm-bar="false"
          />
          <view class="char-count">{{ formData.remarks?.length || 0 }}/200</view>
        </view>

        <!-- 图片上传 -->
        <view class="form-item">
          <view class="label">上传图片（最多3张）</view>
          <view class="upload-container">
            <s-uploader
              v-model:url="formData.urls"
              fileMediatype="image"
              limit="3"
              mode="grid"
              :imageStyles="{ width: '168rpx', height: '168rpx' }"
            />
          </view>
        </view>
      </view>

      <!-- 底部按钮 -->
      <view class="modal-footer">
        <button class="cancel-btn" @tap="handleCancel">取消</button>
        <button
          class="confirm-btn"
          @tap="handleConfirm"
          :disabled="loading"
        >
          {{ loading ? '提交中...' : '确认提交' }}
        </button>
      </view>
    </view>
  </view>
</template>

<script setup>
  import { ref, reactive, watch } from 'vue';
  import ReservationApi from '@/sheep/api/reservation/reservation';

  // Props
  const props = defineProps({
    modelValue: {
      type: Boolean,
      default: false
    },
    reservationData: {
      type: Object,
      default: () => ({})
    }
  });

  // Emits
  const emit = defineEmits(['update:modelValue', 'success']);

  // 响应式数据
  const show = ref(false);
  const loading = ref(false);
  const formData = reactive({
    reservationId: null,
    urls: [],
    remarks: ''
  });

  // 监听 modelValue 变化
  watch(() => props.modelValue, (newVal) => {
    show.value = newVal;
    if (newVal && props.reservationData) {
      formData.reservationId = props.reservationData.id;
      // 重置表单数据
      formData.urls = [];
      formData.remarks = '';
    }
  });

  // 监听 show 变化
  watch(show, (newVal) => {
    emit('update:modelValue', newVal);
  });

  // 遮罩点击处理
  function handleMaskClick() {
    // 可以选择是否允许点击遮罩关闭
    // handleCancel();
  }

  // 选择图片
  function chooseImage() {
    const remainingCount = 3 - formData.urls.length;

    uni.chooseImage({
      count: remainingCount,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        // 这里需要调用上传接口，获取图片URL
        uploadImages(res.tempFilePaths);
      },
      fail: (err) => {
        console.error('选择图片失败:', err);
        uni.showToast({
          title: '选择图片失败',
          icon: 'none'
        });
      }
    });
  }

  // 上传图片到服务器
  async function uploadImages(tempFilePaths) {
    uni.showLoading({
      title: '上传中...'
    });

    try {
      for (const filePath of tempFilePaths) {
        // 这里需要根据您的实际上传接口进行调整
        const uploadResult = await uploadSingleImage(filePath);
        if (uploadResult) {
          formData.urls.push(uploadResult);
        }
      }
    } catch (error) {
      console.error('上传失败:', error);
      uni.showToast({
        title: '上传失败，请重试',
        icon: 'none'
      });
    } finally {
      uni.hideLoading();
    }
  }

  // 单个图片上传（需要根据实际接口调整）
  function uploadSingleImage(filePath) {
    return new Promise((resolve, reject) => {
      uni.uploadFile({
        url: 'YOUR_UPLOAD_API_URL', // 替换为您的上传接口地址
        filePath: filePath,
        name: 'file',
        header: {
          // 添加必要的请求头，如token等
        },
        success: (res) => {
          try {
            const data = JSON.parse(res.data);
            if (data.code === 0) {
              resolve(data.data.url); // 根据实际返回结构调整
            } else {
              reject(new Error(data.message || '上传失败'));
            }
          } catch (error) {
            reject(error);
          }
        },
        fail: (error) => {
          reject(error);
        }
      });
    });
  }

  // 删除图片
  function removeImage(index) {
    formData.urls.splice(index, 1);
  }

  // 取消操作
  function handleCancel() {
    show.value = false;
    // 重置表单数据
    formData.urls = [];
    formData.remarks = '';
  }

  // 确认提交
  async function handleConfirm() {
    if (loading.value) return;

    try {
      loading.value = true;

      // 调用完成预约接口
      const { code, data } = await ReservationApi.completeReservation({
        reservationId: formData.reservationId,
        urls: formData.urls,
        remarks: formData.remarks
      });

      if (code === 0) {
        uni.showToast({
          title: '核销成功',
          icon: 'success'
        });

        // 关闭弹窗
        show.value = false;

        // 通知父组件刷新数据
        emit('success');

        // 重置表单数据
        formData.urls = [];
        formData.remarks = '';
      } else {
        uni.showToast({
          title: '核销失败，请重试',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('核销失败:', error);
      uni.showToast({
        title: '核销失败，请重试',
        icon: 'none'
      });
    } finally {
      loading.value = false;
    }
  }
</script>

<style lang="scss" scoped>
  .modal-mask {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 9999;
  }

  .modal-container {
    width: 600rpx;
    max-height: 80vh;
    background-color: #fff;
    border-radius: 16rpx;
    overflow: hidden;
  }

  .modal-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 30rpx 40rpx;
    border-bottom: 1rpx solid #e5e5e5;

    .modal-title {
      font-size: 32rpx;
      font-weight: 600;
      color: #333;
    }

    .modal-close {
      width: 40rpx;
      height: 40rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 40rpx;
      color: #999;
      cursor: pointer;
    }
  }

  .modal-content {
    padding: 40rpx;
    max-height: 60vh;
    overflow-y: auto;
  }

  .form-item {
    margin-bottom: 40rpx;

    .label {
      font-size: 28rpx;
      color: #333;
      margin-bottom: 20rpx;
      font-weight: 500;
    }

    .textarea {
      width: 100%;
      min-height: 120rpx;
      padding: 20rpx;
      border: 2rpx solid #e5e5e5;
      border-radius: 8rpx;
      font-size: 26rpx;
      color: #333;
      background-color: #fff;
      box-sizing: border-box;

      &:focus {
        border-color: #007aff;
      }
    }

    .char-count {
      text-align: right;
      font-size: 24rpx;
      color: #999;
      margin-top: 10rpx;
    }
  }

  .upload-container {
    .upload-grid {
      display: flex;
      flex-wrap: wrap;
      gap: 20rpx;
    }

    .upload-item {
      position: relative;
      width: 160rpx;
      height: 160rpx;

      .upload-image {
        width: 100%;
        height: 100%;
        border-radius: 8rpx;
        background-color: #f5f5f5;
      }

      .delete-btn {
        position: absolute;
        top: -10rpx;
        right: -10rpx;
        width: 40rpx;
        height: 40rpx;
        background-color: #ff4757;
        color: #fff;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 24rpx;
        cursor: pointer;
      }
    }

    .upload-btn {
      width: 160rpx;
      height: 160rpx;
      border: 2rpx dashed #ddd;
      border-radius: 8rpx;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      cursor: pointer;

      &:hover {
        border-color: #007aff;
      }

      .upload-icon {
        font-size: 40rpx;
        color: #999;
        margin-bottom: 10rpx;
      }

      .upload-text {
        font-size: 24rpx;
        color: #999;
      }
    }
  }

  .modal-footer {
    display: flex;
    gap: 20rpx;
    padding: 30rpx 40rpx;
    border-top: 1rpx solid #e5e5e5;

    button {
      flex: 1;
      //height: 80rpx;
      border-radius: 8rpx;
      font-size: 28rpx;
      border: none;

      &.cancel-btn {
        background-color: #f5f5f5;
        color: #666;
      }

      &.confirm-btn {
        background: linear-gradient(90deg, #ff6b35 0%, #f7931e 100%);
        color: #fff;

        &:disabled {
          opacity: 0.6;
          background: #ccc;
        }
      }
    }
  }
</style>

